import PropTypes from 'prop-types'
import { history } from 'umi'
import { connect } from 'umi'
import React, { PureComponent } from 'react'
import {Button, Tree, Row, Col, Space} from "antd"
import {Page} from "../../components";
import ResourceItem from "./components/ResourceItem";
import {stringify} from "qs";
import TreeNodeModal from "./components/TreeNodeModal";
import {t} from "@lingui/macro";
import Filter from "./components/Filter";


@connect(({ resource, loading }) => ({ resource, loading }))
class Resource extends PureComponent {

  /**
   * 刷新页面句柄
   * @param newQuery
   */
  handleRefresh = () => {
    const { location } = this.props
    const { query, pathname } = location
    history.push({
      pathname,
      search: stringify(
        {
          ...query
        },
        { arrayFormat: 'repeat' }
      ),
    })
  }

  onSelect = (info) => {
    console.log(info);
  };

  onCheck = (info) => {
    console.log(info);
  };

  get treeNodeProps() {
    const { dispatch } = this.props
    const handleRefresh = this.handleRefresh
    return {
      //创建子菜单
      onCreate(parentId) {
        dispatch({
          type: "resource/queryDetails",
          payload: {modalType:"create", item:{parentId:parentId}},
        }).then(() => {
          handleRefresh()
        })
      },

      //更新菜单
      onUpdate(item){
        dispatch({
          type: "resource/queryDetails",
          payload: {modalType:"update", item:{id:item.id}},
        }).then(() => {
          handleRefresh()
        })
      },

      //删除记录
      onDelete(item){
        dispatch({
          type: "resource/delete",
          payload: {id:item.id},
        }).then(() => {
          handleRefresh()
        })
      },
    }
  }

  //获取递归树
  getTreeNode = (item, actions) => {
    //递归获取数据
    function getTree(child) {
      if(child == null) {
        return {}
      }
      const cheildrenArray = [];
      if(child && child.children && child.children.length>0) {
        const children = child.children
        for (let i = 0; i < children.length; i++) {
          let son = getTree(children[i])
          if(son) {
            cheildrenArray.push(son)
          }
        }
      }
      return {
        title: <ResourceItem {...actions} item={{id:child && child.key !=null ? child.key : null}} title={child.title} />,
        key: child && child.key !=null ? child.key : null,
        blockNode: true,
        children: cheildrenArray,
      };
    }

    return getTree(item);
  };

  get modalProps() {
    const { dispatch, resource, loading } = this.props
    const { currentItem, modalVisible, modalType } = resource
    return {
      item: modalType === 'create' ? {breadcrumbParentId:currentItem.parentId} : currentItem,
      visible: modalVisible,
      destroyOnClose: true,
      maskClosable: false,
      confirmLoading: loading.effects[`resource/${modalType}`],
      title: `${
        modalType === 'create' ? t`Create Resource` : t`Update Resource`
      }`,
      centered: true,
      onOk: data => {
        dispatch({
          type: `resource/${modalType}`,
          payload: data,
        }).then(() => {
          this.handleRefresh()
        })
      },
      onCancel() {
        dispatch({
          type: 'resource/hideModal',
        })
      },
    }
  }

  get filterProps() {
    const { dispatch, resource, loading } = this.props
    const {syncResource} = resource;

    return {
      onSync: ()=>{
        //TODO auto sync menu
        dispatch({type: "resource/syncResource"}).then((data)=>{
          //todo message
          this.handleRefresh()
        });
      }
    }
  }

  render() {
    const {resource} = this.props
    const {tree} = resource
    const allTree = this.getTreeNode(tree,this.treeNodeProps)

    return (
      <Page inner>
        <Filter {...this.filterProps} />
        <Tree
          defaultExpandAll={true}
          checkable
          blockNode={true}
          autoExpandParent={true}
          defaultExpandedKeys={[]}
          defaultSelectedKeys={[]}
          defaultCheckedKeys={[]}
          onSelect={this.onSelect}
          onCheck={this.onCheck}
          treeData={[allTree]}
        />
        <TreeNodeModal {...this.modalProps} />
      </Page>

    );
  }
}


Resource.propTypes = {
  resource: PropTypes.object,
  loading: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
}

export default Resource
